import Vue from 'vue'
import Vuex from 'vuex'
import {
  getList,
  getMe,
  getStores,
  getRegion,
  bind,
  getQues
} from 'api'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    ques: {},
    quesStatus: {},
    quesList: [],
    answerList: [],
    hasAnswer: false,
    stores: [],
    region: [],
    info: null,
    passed: false,
    num: 0,
    failArr: [],
    quesListId: '',
    exObj: {}
  },
  mutations: {
    SET_QUES_LIST(state, list) {
      state.quesList = list.sort((a, b) => b.id - a.id)
    },
    SET_ANSWER_LIST(state, list) {
      state.answerList = list
    },
    SET_QUES_STATUS(state, status) {
      state.quesStatus = status
    },
    SET_ANSWER(state, status) {
      state.hasAnswer = status
    },
    SET_INFO(state, status) {
      state.info = status
    },
    SET_STORES(state, stores) {
      state.stores = stores
    },
    SET_REGION(state, stores) {
      state.region = stores
    },
    SELECT_QUES(state, ques) {
      state.ques = ques
    },
    SET_PASS(state, status) {
      state.passed = status
    },
    SET_RIGHT(state, num) {
      state.num = num
    },
    SET_FAIL(state, num) {
      state.failArr = num
    },
    SET_QUES_LIST_ID(state, id) {
      state.quesListId = id
    },
    SET_EXAM_OBJ(state, exObj) {
      state.exObj = exObj
    },
  },
  actions: {
    async GetList({
      commit,
      state
    }) {
      let res = await getList(state.info)
      commit('SET_QUES_LIST', res.results.filter(v => !state.failArr.includes(v.id)))
    },
    async GetMe({
      commit
    }) {
      let res = await getMe()
      res['id'] ? commit('SET_INFO', res) : commit('SET_INFO', null)
      return !!res['id']
    },
    async Bind({
      commit
    }, pramas) {
      let res = await bind(pramas)
      res['id'] ? commit('SET_INFO', res) : commit('SET_INFO', null)
      return !!res['id']
    },
    async GetStores({
      commit
    }) {
      let res = await getStores()
      commit('SET_STORES', res.results)
      return res
    },
    async GetRegion({
      commit
    }) {
      let res = await getRegion()
      commit('SET_REGION', res)
    },
    async GetQues({
      commit
    }, pramas) {
      commit('SET_QUES_LIST_ID', pramas.id)
      let res = await getQues(pramas)
      if (res) {
        commit('SELECT_QUES', res.quests.map(v => v = {
          ...v,
          subject: v.subject.split('{}').length > 2 ? v.subject.split('{}') : v.subject.replace(/{}/g, '____')
        }))
        commit('SET_EXAM_OBJ', res)
      }
    }
  },
  getters: {
    quesList: state => state.quesList,
    answerList: state => state.answerList,
    stores: state => state.stores,
    region: state => state.region,
    ques: state => state.ques,
    info: state => state.info,
    passed: state => state.passed,
    num: state => state.num,
    failArr: state => state.failArr,
    quesListId: state => state.quesListId,
    quesStatus: state => state.quesStatus,
    exObj: state => state.exObj
  }
})